﻿using Models.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Web.Filters;
using System.IO;
using FreeADO.Common;

namespace Web.Controllers.MVC
{
    [MvcAuthentication]
    public class DefaultController : Controller
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        // GET: Default
        public ActionResult Index()
        {
            
            ViewBag.UserName = Common.CookiesManagement.GetUserModel().UserName;
            return View();
        }

        public string Init()
        {
            var info = Web.Common.Common.GetInitInfoModel();
            return Newtonsoft.Json.JsonConvert.SerializeObject(info);
        }
        /// <summary>
        /// 登录页面
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Login()
        {
            //string pyCode = FreeADO.Common.StringPlus.GetFirstPYLetter("供应商");

            //string fileFullName = "D:\\企业抽查\\010.jpg";
            //string rMarkText = "2023/07/24 09:11:25|周丽娟|四川省成都市武侯区|桂溪街道德商国际桂溪街道德商国际桂溪街道德商国际桂溪街道德商国际桂溪街道德商国际|自定义文本内容";
            //PictureHelper.BuildWatermark01(fileFullName, rMarkText);

            //PictureHelper.BuildWatermark(fileFullName, rMarkText);

            //string connectionString = "Server=114.116.37.247;Database=sjtsjjd;Uid=sa;Pwd=Syqt20992099";
            //string strSQL = "select IsItGift,FullName from ptype where UserCode ='66666678'";
            //DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
            //if (string.IsNullOrWhiteSpace(dt.Rows[0]["IsItGift"].ToString()))
            //{
            //    //|| dt.Rows[0]["IsItGift"].ToString() == "False"
            //    string aaa = "";
            //}


            //FormsAuthentication.SignOut();
            return View();
        }
        [AllowAnonymous]
        public ActionResult Captcha()
        {
            string Captcha = FreeADO.Common.StringPlus.CreateRandomNum(4);
            Session["Captcha"] = Captcha;
            var image = FreeADO.Common.StringPlus.CreateImage(Captcha);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            //将图像保存到指定的流
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            Response.ClearContent();
            Response.ContentType = "image/Gif";
            Response.BinaryWrite(ms.ToArray());
            return View();
        }
        [HttpPost, AllowAnonymous]
        public ActionResult LoginAsync(string LoginName, string LoginPass, string Captcha, int RememberMe = 0)
        {
            Result<string> result = new Result<string>();
            if (Captcha.ToUpper() != Session["Captcha"].ToString().ToUpper())
            {
                result.Type = AjaxResultType.Error;
                result.Content = "验证码错误";
            }
            else
            {
                DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query("select Logins.LoginPass,Logins.UserID,Users.UserName from Logins inner join Users on Logins.UserID=Users.ID where Logins.LoginType=1 and Logins.LoginName='" + LoginName + "' and Logins.IsDeleted=0 and Users.IsDeleted=0").Tables[0];
                if (dt.Rows.Count != 1)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "登录名错误";
                }
                else if (dt.Rows[0]["LoginPass"].ToString() != LoginPass)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "密码错误";
                }
                else
                {
                    Models.Common.CookiesUserModel m = new CookiesUserModel();
                    m.LoginName = LoginName;
                    m.UserID = Convert.ToInt32(dt.Rows[0]["UserID"]);
                    m.UserName = Convert.ToString(dt.Rows[0]["UserName"]);
                    result.Type = AjaxResultType.Success;
                    result.Content = "登录成功";

                    var data = Newtonsoft.Json.JsonConvert.SerializeObject(m);
                    var ticket = new FormsAuthenticationTicket(
                                        1,
                                        LoginName,
                                        DateTime.Now,
                                        DateTime.Now.Add(FormsAuthentication.Timeout),
                                        RememberMe == 1 ? true : false,
                                        data);
                    var cookie = new HttpCookie(
                        FormsAuthentication.FormsCookieName,
                        FormsAuthentication.Encrypt(ticket));
                    cookie.HttpOnly = true;
                    Response.Cookies.Add(cookie);

                }
            }
            return Json(result);
        }

        public ActionResult GoodsList()
        {
            return View();
        }
        [HttpPost]
        public string GoodsListAsync(int PageIndex = 1, int PageSize = 20, string Search = "")
        {
            GridResult result = new GridResult();
            SqlParameter[] parameters = {
                                            new SqlParameter("@PageIndex",SqlDbType.Int),
                                            new SqlParameter("@PageSize",SqlDbType.Int),
                                            new SqlParameter("@Search",SqlDbType.NVarChar,40000)};
            parameters[0].Value = PageIndex;
            parameters[1].Value = PageSize;
            parameters[2].Value = Search;
            DataSet ds = FreeADO.DBUtility.DbHelperSQL.RunProcedure("SP_QueryGoodsList", parameters, "aaa", 3000);
            result.count = Convert.ToInt32(ds.Tables[0].Rows[0]["count"]);
            result.data = ds.Tables[1];
            result.totalRow = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(Newtonsoft.Json.JsonConvert.SerializeObject(ds.Tables[2]))[0];
            return Newtonsoft.Json.JsonConvert.SerializeObject(result);
        }


        
    }
}